package part10;

/**
 * @author wcj
 * @Date 2021/5/19 18:46
 * @Version 1.0
 */
public class Part111 {

    public static void main(String[] args) {
        Callee1 callee1 = new Callee1();
        Callee2 callee2 = new Callee2();
        MyIncrement.f(callee2);
        Caller caller1 = new Caller(callee1);
        Caller caller2 = new Caller(callee2.getCallbackReference());
        caller1.go();
        caller1.go();
        caller2.go();
        caller2.go();
    }
}

interface IncrementAble {

    /**
     * increment
     */
    void increment();
}

/**
 * 简单的实现接口
 */
class Callee1 implements IncrementAble {
    private int i = 0;

    @Override
    public void increment() {
        i++;
        System.out.println(i);
    }
}

class MyIncrement {
    public void increment() {
        System.out.println("Other Operation");
    }

    static void f(MyIncrement mi) {
        mi.increment();
    }
}

/**
 * 接口和MyIncrement类中都有一个increment函数，当jie'jue'fan's我们想要实现自己的increment时，但是又同时需要实现这个接口的时候
 * 使用内部类就是很好的一个解决方式
 */
class Callee2 extends MyIncrement{
    private int i = 0;

    @Override
    public void increment() {
        super.increment();
        i++;
        System.out.println(i);
    }

    private class Closure implements IncrementAble {

        @Override
        public void increment() {
            Callee2.this.increment();
        }
    }

    IncrementAble getCallbackReference() {
        return new Closure();
    }
}

class Caller {
    private IncrementAble callbackReference;

    Caller(IncrementAble cbh) {
        this.callbackReference = cbh;
    }

    void go() {
        callbackReference.increment();
    }
}
